<?php
namespace app\controller;

use support\Request;
use support\Db;

class AccountBookController
{
    /**
     * 创建账本时自动添加创建者为管理员
     */
    public function create(Request $request)
    {
        try {
            Db::beginTransaction();
            
            $data = [
                'user_id' => $request->uid,
                'name' => $request->post('name'),
                'description' => $request->post('description', ''),
                'created_at' => date('Y-m-d H:i:s')
            ];

            if (empty($data['name'])) {
                return json([
                    'code' => 400,
                    'msg' => '账本名称不能为空'
                ]);
            }

            // 创建账本
            $bookId = Db::table('account_books')->insertGetId($data);
            
            // 添加创建者为管理员
            Db::table('account_book_users')->insert([
                'book_id' => $bookId,
                'user_id' => $request->uid,
                'role' => 1, // 管理员
                'created_at' => date('Y-m-d H:i:s')
            ]);

            Db::commit();
            return json([
                'code' => 0,
                'msg' => '创建成功',
                'data' => ['id' => $bookId]
            ]);
        } catch (\Exception $e) {
            Db::rollBack();
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取用户参与的所有账本
     */
    public function list(Request $request)
    {
        try {
            $list = Db::table('account_books as b')
                ->join('account_book_users as bu', 'b.id', '=', 'bu.book_id')
                ->where('bu.user_id', $request->uid)
                ->where('b.status', 1)
                ->where('bu.status', 1)
                ->select([
                    'b.id',
                    'b.name',
                    'b.description',
                    'b.user_id as creator_id',
                    'bu.role',
                    'b.created_at'
                ])
                ->orderBy('b.created_at', 'desc')
                ->get();

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 添加账本成员
     */
    public function addMember(Request $request)
    {
        try {
            $bookId = $request->post('book_id');
            $userId = $request->post('user_id');
            
            // 验证是否为管理员
            $isAdmin = Db::table('account_book_users')
                ->where('book_id', $bookId)
                ->where('user_id', $request->uid)
                ->where('role', 1)
                ->where('status', 1)
                ->exists();

            if (!$isAdmin) {
                return json([
                    'code' => 403,
                    'msg' => '无权限添加成员'
                ]);
            }

            // 添加成员
            Db::table('account_book_users')->insert([
                'book_id' => $bookId,
                'user_id' => $userId,
                'role' => 0, // 普通成员
                'created_at' => date('Y-m-d H:i:s')
            ]);

            return json([
                'code' => 0,
                'msg' => '添加成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 移除账本成员
     */
    public function removeMember(Request $request)
    {
        try {
            $bookId = $request->post('book_id');
            $userId = $request->post('user_id');
            
            // 验证是否为管理员
            $isAdmin = Db::table('account_book_users')
                ->where('book_id', $bookId)
                ->where('user_id', $request->uid)
                ->where('role', 1)
                ->where('status', 1)
                ->exists();

            if (!$isAdmin) {
                return json([
                    'code' => 403,
                    'msg' => '无权限移除成员'
                ]);
            }

            // 不能移除管理员
            $targetUser = Db::table('account_book_users')
                ->where('book_id', $bookId)
                ->where('user_id', $userId)
                ->first();

            if ($targetUser->role == 1) {
                return json([
                    'code' => 400,
                    'msg' => '不能移除管理员'
                ]);
            }

            // 移除成员（软删除）
            Db::table('account_book_users')
                ->where('book_id', $bookId)
                ->where('user_id', $userId)
                ->update([
                    'status' => 0,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

            return json([
                'code' => 0,
                'msg' => '移除成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取账本成员列表
     */
    public function members(Request $request)
    {
        try {
            $bookId = $request->get('book_id');
            
            $members = Db::table('account_book_users as bu')
                ->join('wa_users as u', 'bu.user_id', '=', 'u.id')
                ->where('bu.book_id', $bookId)
                ->where('bu.status', 1)
                ->select([
                    'u.id',
                    'u.nickname',
                    'u.avatar',
                    'bu.role',
                    'bu.created_at'
                ])
                ->get();

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $members
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取账本详情
     */
    public function detail(Request $request)
    {
        try {
            $bookId = $request->get('id');
            if (empty($bookId)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 获取账本信息和成员数量
            $book = Db::table('account_books as b')
                ->leftJoin('wa_users as u', 'b.user_id', '=', 'u.id')
                ->leftJoin('account_book_users as bu', function($join) {
                    $join->on('b.id', '=', 'bu.book_id')
                         ->where('bu.status', 1);
                })
                ->where('b.id', $bookId)
                ->where('b.status', 1)
                ->select([
                    'b.id',
                    'b.name',
                    'b.description',
                    'b.user_id as creator_id',
                    'u.nickname as creator_name',
                    'b.created_at',
                    Db::raw('COUNT(DISTINCT bu.user_id) as member_count')
                ])
                ->groupBy('b.id')
                ->first();

            if (!$book) {
                return json([
                    'code' => 404,
                    'msg' => '账本不存在'
                ]);
            }

            // 获取当前用户在该账本的角色
            $userRole = Db::table('account_book_users')
                ->where('book_id', $bookId)
                ->where('user_id', $request->uid)
                ->where('status', 1)
                ->value('role');

            if ($userRole === null) {
                return json([
                    'code' => 403,
                    'msg' => '无权限查看'
                ]);
            }

            $book->is_admin = $userRole == 1;

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $book
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 更新账本信息
     */
    public function update(Request $request)
    {
        try {
            $id = $request->post('id');
            $name = $request->post('name');
            $description = $request->post('description');

            if (empty($id) || empty($name)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 验证是否为管理员
            $isAdmin = Db::table('account_book_users')
                ->where('book_id', $id)
                ->where('user_id', $request->uid)
                ->where('role', 1)
                ->where('status', 1)
                ->exists();

            if (!$isAdmin) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            // 更新账本信息
            Db::table('account_books')
                ->where('id', $id)
                ->update([
                    'name' => $name,
                    'description' => $description,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

            return json([
                'code' => 0,
                'msg' => '更新成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 删除账本（软删除）
     */
    public function delete(Request $request)
    {
        try {
            $id = $request->post('id');
            if (empty($id)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 验证是否为管理员
            $isAdmin = Db::table('account_book_users')
                ->where('book_id', $id)
                ->where('user_id', $request->uid)
                ->where('role', 1)
                ->where('status', 1)
                ->exists();

            if (!$isAdmin) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            Db::beginTransaction();
            try {
                // 软删除账本
                Db::table('account_books')
                    ->where('id', $id)
                    ->update([
                        'status' => 0,
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);

                // 移除所有成员关联
                Db::table('account_book_users')
                    ->where('book_id', $id)
                    ->update([
                        'status' => 0,
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);

                // 清除用户的默认账本（如果是）
                Db::table('wa_users')
                    ->where('default_book_id', $id)
                    ->update([
                        'default_book_id' => null,
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);

                Db::commit();
                return json([
                    'code' => 0,
                    'msg' => '删除成功'
                ]);
            } catch (\Exception $e) {
                Db::rollBack();
                throw $e;
            }
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }
} 